package me.ingxin.android.permission2.ext

import android.content.Context
import android.os.Handler
import android.os.Looper
import me.ingxin.android.permission2.request.Request
import me.ingxin.android.permission2.request.RequestNormalFragment
import me.ingxin.android.permission2.request.Task
import me.ingxin.android.permission2.request.TaskChain
import me.ingxin.android.permission2.specialPermissionGranted
import me.ingxin.android.permission2.strategy.ReasonStrategy
import me.ingxin.android.permission2.view.Guide
import me.ingxin.android.permission2.view.GuideView

/**
 * Created on 2023/7/16 by yin
 * 需要申请的权限要先获取到普通基础权限才能申请成功
 */
internal abstract class PlusNormalPermissionTask : Task {

    private val mainHandler = Handler(Looper.getMainLooper())
    private var whileView: GuideView? = null
    private var settingsView: GuideView? = null

    /**需要请求的权限*/
    abstract val permission: String

    override fun runTask(chain: TaskChain, request: Request) {
        if (!shouldRequest(chain.context, request)) {
            chain.proceed(request)
            return
        }
        if (request.reasonStrategy == ReasonStrategy.Before) {
            showReasonView(chain, request)
        } else {
            requestPermission(chain, request)
        }
    }

    private fun showReasonView(chain: TaskChain, request: Request) {
        request.guide.getShowReasonView(chain.context, listOf(permission), {
            it.applyDismiss()
            requestPermission(chain, request)
        }) {
            it.applyDismiss()
            //用户拒绝，执行下一个任务
            chain.proceed(request)
        }.applyShow()
    }

    private fun showReasonViewWhileRequest(
        context: Context, permissions: List<String>, explanation: Guide
    ) {
        whileView = explanation.getTipsView(context, permissions)
        whileView?.applyShow()
    }

    private fun toSettings(chain: TaskChain, request: Request, notShownList: List<String>) {
        settingsView = request.guide.getToSettingsView(chain.context, notShownList, {
            //用户选择去设置中心
            it.applyDismiss()
            val fragment = RequestNormalFragment()
            fragment.requestToSettings { requestPermission(chain, request) }
            chain.fragmentManager.beginTransaction().add(fragment, fragment.javaClass.name)
                .commitAllowingStateLoss()
        }) {
            //用户拒绝去设置中心
            it.applyDismiss()
            chain.proceed(request)
        }
        settingsView?.applyShow()
    }

    /**
     * 是否获取到了基础权限
     */
    abstract fun hasBasePermission(context: Context): Boolean

    private fun shouldRequest(context: Context, request: Request): Boolean {
        return request.specialPermissions.contains(permission) && hasBasePermission(context) && !context.specialPermissionGranted(
            permission
        )
    }

    private fun requestPermission(chain: TaskChain, request: Request) {
        whileView?.applyDismiss()
        settingsView?.applyDismiss()

        if (!shouldRequest(chain.context, request)) {
            chain.proceed(request)
            return
        }

        if (request.tipsWhileRequest) {
            //当用户选择了不再询问时，可能不会弹出系统框被直接拒绝，等待一小段时间，过滤这种情况
            //todo 某些机型特殊权限是跳转到设置页面，就可能导致从设置页面回来时，顶部对话框一闪而而过，待解决
            mainHandler.postDelayed({
                showReasonViewWhileRequest(
                    chain.context, listOf(permission), request.guide
                )
            }, 350)
        }

        val fragment = RequestNormalFragment()
        fragment.requestNormalPermissions(listOf(permission)) { _, _, notShownList ->
            mainHandler.removeCallbacksAndMessages(null)
            whileView?.applyDismiss()
            if (request.settings && notShownList.isNotEmpty()) {
                toSettings(chain, request, notShownList)
            } else {
                chain.proceed(request)
            }
        }
        chain.fragmentManager.beginTransaction().add(fragment, fragment.javaClass.name)
            .commitAllowingStateLoss()
    }

}